package com.tsfyun.scm.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tsfyun.scm.gateway.constant.LimitConstant;
import com.tsfyun.scm.gateway.util.FrequencyUtil;
import com.tsfyun.scm.gateway.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Description:
 * @CreateDate: Created in 2020/12/7 15:48
 */
public class FrequencyCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String host = StrUtil.nullToEmpty(exchange.getRequest().getHeaders().getFirst("Host"));
        //此处只有客户端才校验，小程序，管理端等均不验证
        Boolean isMobile = IpUtils.isMobile(exchange.getRequest());
        if(isMobile || host.contains("manage")) {
            return chain.filter(exchange);
        }
        String limitRequestId = exchange.getRequest().getHeaders().getFirst("limitRequestId");
        if(StringUtils.isEmpty(limitRequestId) || Objects.equals("null",StrUtil.nullToEmpty(limitRequestId).toLowerCase()) ) {
            return chain.filter(exchange);
        }
        //获取是否操作频繁被强制验证
        String isLimitCheck = stringRedisTemplate.opsForValue().get(LimitConstant.FREQUENCY_LIMIT + limitRequestId);
        if(StringUtils.isEmpty(isLimitCheck)) {
            return chain.filter(exchange);
        }
        exchange.getResponse().setStatusCode(HttpStatus.OK);
        JSONObject resultJson = FrequencyUtil.wrapResult(limitRequestId);
        byte[] bytes = resultJson.toJSONString().getBytes(StandardCharsets.UTF_8);
        exchange.getResponse().getHeaders().add("Content-Type","application/json;charset=UTF-8");
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -900;
    }
}
